package com.dingwei.superiordiary.mvp.presenter;

import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.dingwei.superiordiary.base.MyBaseBean;
import com.dingwei.superiordiary.bean.FailsBean;
import com.dingwei.superiordiary.custom.myCallback;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.weight.UploadVideoDialog;
import com.guoxiaoxing.phoenix.compress.video.VideoCompressor;
import com.guoxiaoxing.phoenix.compress.video.format.MediaFormatStrategyPresets;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.base.URLS;
import com.lihao.baselibrary.base.basePresenter;
import com.lihao.baselibrary.utils.ImageUtils;
import com.lihao.baselibrary.utils.L;
import com.luck.picture.lib.entity.LocalMedia;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author lihao
 * @date 2017/9/12
 */

public class ReleaseCommunityPresenter extends basePresenter {

    private Contract.ReleaseCommunityView releaseCommunityView;

    public ReleaseCommunityPresenter(Contract.ReleaseCommunityView view) {
        super(view);
        this.releaseCommunityView = view;
    }

    public void save(List<LocalMedia> photoList, final LocalMedia video_path, String type, String content) {


        if (TextUtils.isEmpty(content)) {
            showToast("请输入内容");
            return;
        }

        final RequestParams rp = new RequestParams(URLS.HOST + URLS.RELEASE_COMMUNITY);
        rp.addBodyParameter("sessionid", BaseActivity.value.getToken());
        rp.addBodyParameter("type", type);
        rp.addBodyParameter("content", content);


        if (video_path!=null&&!TextUtils.isEmpty(video_path.getPath())) {
            rp.addBodyParameter("video_image", ImageUtils.compressImage(ImageUtils.getVideoThumbnail(video_path.getPath(), 300, 150, MediaStore.Images.Thumbnails.MICRO_KIND)));
            final UploadVideoDialog prosDialog = new UploadVideoDialog(BaseActivity.context);
            prosDialog.show();
            prosDialog.setHint("正在压缩...");
            final File compressFile;
            try {
                File compressCachePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "phoenix");
                compressCachePath.mkdir();
                compressFile = File.createTempFile("compress", ".mp4", compressCachePath);
            } catch (IOException e) {
                showToast("Failed to create temporary file.");
                return;
            }
            try {
                VideoCompressor.with().asyncTranscodeVideo(video_path.getPath(), compressFile.getAbsolutePath(),
                        MediaFormatStrategyPresets.createAndroid480pFormatStrategy(), new VideoCompressor.Listener() {
                            @Override
                            public void onTranscodeProgress(double progress) {
                                L.e("progress =" + progress);
                                prosDialog.setProgress((int) (progress * 100));
                            }

                            @Override
                            public void onTranscodeCompleted() {
                                if (compressFile != null && compressFile.exists()) {
                                    L.e("size = " + compressFile.length());
                                    rp.addBodyParameter("video", compressFile);
                                    x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, false, rp) {
                                        @Override
                                        public void back(MyBaseBean baseBean, String result) {
                                            prosDialog.dismiss();
                                            releaseCommunityView.saveSuccess();
                                        }

                                        @Override
                                        public void onLoading(long total, long current, boolean isUploading) {
                                            super.onLoading(total, current, isUploading);

                                            prosDialog.setProgress((int) (current / (total / 100)));
                                            if ((int) (current / (total / 100)) < 100) {
                                                prosDialog.setHint("正在上传...");
                                            } else {
                                                prosDialog.setHint("服务器处理中...");
                                            }
                                        }

                                        @Override
                                        public void fail(FailsBean baseBean, String result) {
                                            showToast(result);
                                            prosDialog.dismiss();
                                        }
                                    });
                                } else {
                                    return;
                                }

                            }

                            @Override
                            public void onTranscodeCanceled() {
                            }

                            @Override
                            public void onTranscodeFailed(Exception exception) {
                                File file = new File(video_path.getPath());
                                if (file != null && file.exists()) {
                                    L.e("size = " + file.length());
                                    rp.addBodyParameter("video", file);
                                } else {
                                    return;
                                }

                                x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, false, rp) {
                                    @Override
                                    public void back(MyBaseBean baseBean, String result) {
                                        prosDialog.dismiss();
                                        releaseCommunityView.saveSuccess();
                                    }

                                    @Override
                                    public void onLoading(long total, long current, boolean isUploading) {
                                        super.onLoading(total, current, isUploading);

                                        prosDialog.setProgress((int) (current / (total / 100)));
                                        if ((int) (current / (total / 100)) < 100) {
                                            prosDialog.setHint("正在上传...");
                                        } else {
                                            prosDialog.setHint("服务器处理中...");
                                        }
                                    }

                                    @Override
                                    public void fail(FailsBean baseBean, String result) {
                                        showToast(result);
                                        prosDialog.dismiss();
                                    }
                                });

                            }
                        });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            if (photoList != null) {
                for (int i = 1; i <= photoList.size(); i++) {
                    if (!TextUtils.isEmpty(photoList.get(i - 1).getCompressPath())) {
                        rp.addBodyParameter("img" + i, new File(photoList.get(i - 1).getCompressPath()));
                    }
                }
            }
            x.http().post(rp, new myCallback(BaseActivity.context, MyBaseBean.class, rp) {
                @Override
                public void back(MyBaseBean baseBean, String result) {
                    showToast(baseBean.message);
                    releaseCommunityView.saveSuccess();
                }

                @Override
                public void fail(FailsBean baseBean, String result) {
                    releaseCommunityView.onFail();

                }
            });
        }

    }


}
